package com.campus.backend.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.campus.backend.bean.AdminUserLoginBean;
import com.campus.backend.entity.AdminUser;
import com.campus.backend.service.AdminUserService;
import com.campus.backend.service.RedisService;
import com.campus.backend.service.SessionService;
import com.campus.backend.vo.UserInfoVo;
import com.campus.common.bean.common.Resp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/adminUser")
@Api(tags = "操作员登录相关接口")
public class AdminUserController {
    @Autowired
    private RedisService redisService;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private SessionService sessionService;

    @ApiOperation("获取登录验证码")
    @GetMapping("/login/code")
    public Resp<Map<String, String>> getLoginCode() {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        String code = lineCaptcha.getCode();
        String codeKey = UUID.randomUUID().toString().replaceAll("-", "");
        redisService.set(codeKey, code, 5 * 60L);
        Map<String, String> result = new HashMap<>();
        result.put("codeKey", codeKey);
        result.put("codeImage", "data:image/jpeg;base64," + lineCaptcha.getImageBase64());
        return Resp.success(result);
    }

    @ApiOperation("操作员登录")
    @PostMapping("/login")
    public Resp login(@Validated @RequestBody AdminUserLoginBean loginBean) {
        String code = loginBean.getCode();
        String codeKey = loginBean.getCodeKey();
        if (StringUtils.isBlank(code) || StringUtils.isBlank(codeKey)) {
            return Resp.error("验证码不能为空");
        }
        String storedCode = redisService.get(codeKey);
        if (!code.equals(storedCode)) {
            return Resp.error("验证码错误");
        }
        redisService.remove(codeKey);
        String username = loginBean.getUsername();
        String password = loginBean.getPassword();

        AdminUser user = adminUserService.getOne(Wrappers.lambdaQuery(AdminUser.class)
                .eq(AdminUser::getUsername, username));
        if (user == null) {
            return Resp.error("用户不存在");
        }
        if (!user.getPassword().equals(sessionService.getMd5Password(password, user.getSalt()))) {
            return Resp.error("密码错误");
        }
        if (user.getStatus() != null && user.getStatus() == 0) {
            return Resp.error("账号已禁用");
        }
        // 生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");

        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(user, userInfoVo);
//        userInfoVo.setToken(token);
        redisService.set(token, JSON.toJSONString(userInfoVo), 2 * 86400L);

        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("userInfo", userInfoVo);
        return Resp.success(data);
    }

    @ApiOperation("获取当前登录用户信息")
    @GetMapping("/info")
    public Resp<UserInfoVo> getUserInfo() {
        return Resp.success(sessionService.getUserInfo());
    }

    @ApiOperation("操作员登出")
    @PostMapping("/logout")
    public Resp logout() {
        redisService.remove(sessionService.getToken());
        return Resp.success();
    }
}
